import pandas as pd
import numpy as np

df_info = pd.read_csv('static/data/typhoon_info_clean.csv')
df_list = pd.read_csv('static/data/typhoon_list.csv')


def wind_speed_top10():
    data = df_info.sort_values(by=['max_wind_speed'], ascending=False).drop_duplicates(['id']).head(10)[
        ['id', 'max_wind_speed']].values.tolist()
    return {
        'name': [df_list[df_list['id'] == i[0]]['cName'].values.tolist()[0] for i in data],
        'value': [i[1] for i in data],
    }


def time_top10():
    d = df_info[df_info['level'].str.contains('台风')].groupby('id').agg({'datetime': ['min', 'max']}).reset_index()
    d['time'] = d['datetime']['max'].astype('datetime64[ns]') - d['datetime']['min'].astype('datetime64[ns]')
    d['time'] = d['time'].apply(lambda x: x / pd.Timedelta(1, 'h'))
    data = d[['id', 'time']].sort_values(by='time', ascending=False).head(10).values.tolist()
    return {
        'name': [df_list[df_list['id'] == i[0]]['cName'].values.tolist()[0] for i in data],
        'value': [i[1] for i in data],
    }


def month_count():
    data = (df_info[df_info['level'].str.contains('台风')].drop_duplicates('id')
            .groupby('month')['id']
            .count()
            .reset_index()
            .rename(columns={'id': 'count'})
            .sort_values(by='month', ascending=True)
            .values
            .tolist()
            )
    return {
        'name': [int(i[0]) for i in data],
        'value': [i[1] for i in data],
    }


def hPa_boxplot():
    month_group = df_info[['month', 'hPa(中心气压)']].groupby('month')
    label = [int(i[0]) for i in month_group]
    value = [[int(j[1]) for j in i[1].values] for i in month_group]
    return {
        'label': label,
        'value': value
    }


def typhoon_level_pie():
    level_to_int = {'热带低压': 1, '热带风暴': 2, '强热带风暴': 3, '台风': 4, '强台风': 5, '超强台风': 6}
    int_to_level = {1: '热带低压', 2: '热带风暴', 3: '强热带风暴', 4: '台风', 5: '强台风', 6: '超强台风'}
    df_info['level_to_int'] = df_info['level'].apply(lambda x: level_to_int.get(x, -1))
    data = df_info.groupby('id')['level_to_int'].max().reset_index().groupby(
        'level_to_int').count().reset_index().values.tolist()
    return {
        'data': [{'name': int_to_level.get(i[0]), 'value': i[1]} for i in data]
    }
